package com.supermap.search.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.supermap.search.R;
import com.yanzhenjie.alertdialog.AlertDialog;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wyw on 2017/3/2.
 * 这是闪屏欢迎界面
 */

public class FlashActivity extends AppCompatActivity {

    private static final String FILE_PATH = "/sdcard/shenzhen/";


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1: //跳转
                    Intent intent = new Intent(FlashActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                    break;
                default:
                    break;
            }

        }
    };
    Map<String, String> map = new HashMap<>();
    private RationaleListener rationaleListener = new RationaleListener() {
        @Override
        public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
            AlertDialog.newBuilder(FlashActivity.this)
                    .setTitle("友好提醒")
                    .setMessage("您已拒绝过相应权限，沒有这些权限无法使用本软件，请授权！")
                    .setPositiveButton("同意", (dialog, which) -> {
                        rationale.resume();
                    })
                    .setNegativeButton("拒绝", (dialog, which) -> {
                        rationale.cancel();
                        finish();
                    }).show();
        }
    };



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flash);


        map.put("android.permission.READ_EXTERNAL_STORAGE", "存储权限");
        map.put("android.permission.ACCESS_FINE_LOCATION", "定位权限");
        map.put("android.permission.CAMERA", "相机权限");
        AndPermission.
                with(this).
                rationale(rationaleListener).
                requestCode(300).
                callback(this).
                permission(
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.CAMERA).
                start();
    }

    private void start() {
        //拷贝db文件到sd卡
        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        copyFile("guanxian.db", android.os.Environment.getExternalStorageDirectory().getPath() + "/shenzhen/db/guanxian.db");
                    }
                }
        ).start();
        handler.sendEmptyMessageDelayed(1, 2000);
    }


    @PermissionYes(300)
    private void getPermissionYes(List<String> grantedPermissions) {
        //申请权限成功。
        start();

    }


    @PermissionNo(300)
    private void getPermissionNo(List<String> deniedPermissions) {
        String msg = "（";
        for (int i = 0; i < deniedPermissions.size(); i++) {
            String permission = deniedPermissions.get(i);
            String s = map.get(permission);
            if (i == deniedPermissions.size() - 1) {
                msg += s + "）";
            } else {
                msg += s + "、";
            }
        }
        // 是否有不再提示并拒绝的权限。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            // 第二种：用自定义的提示语。
            AndPermission.defaultSettingDialog(this, 400)
                    .setTitle("权限申请失败")
                    .setMessage("您拒绝了我们必要的权限" + msg + "，将不能使用本软件，请在设置中授权！")
                    .setPositiveButton("去设置")
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .show();
        } else {
            AndPermission.
                    with(this).
                    rationale(rationaleListener).
                    requestCode(300).
                    callback(this).
                    permission(
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.CAMERA).
                    start();
        }

    }





    public void copyFile(String from, String to) {

        File file = new File(android.os.Environment.getExternalStorageDirectory().getPath() + "/shenzhen/db/");
        if (!file.exists()) {
            try {
                //按照指定的路径创建文件夹
                file.mkdirs();
            } catch (Exception e) {
                // TODO: handle exception
            }
        }

        File dir = new File(android.os.Environment.getExternalStorageDirectory().getPath() + "/shenzhen/db/guanxian.db");
        if (!dir.exists()) {
            try {
                //在指定的文件夹中创建文件
                int bytesum = 0;
                int byteread = 0;
                InputStream inStream = FlashActivity.this.getAssets().open(from);//将assets中的内容以流的形式展示出来
                OutputStream fs = new BufferedOutputStream(new FileOutputStream(to));//to为要写入sdcard中的文件名称
                byte[] buffer = new byte[1024];
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread;
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
                fs.close();
            } catch (Exception e) {
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 400 || requestCode == 100) {
            if (AndPermission.hasPermission(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.CAMERA)) {
                start();
            } else {
                AndPermission.defaultSettingDialog(this, 100);
            }
        }
    }


    /**
     * 沉浸式
     * @param hasFocus
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && Build.VERSION.SDK_INT >= 19) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }
}
